package com.ysalliance.getFan.organization;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.os.Build;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.blankj.utilcode.constant.TimeConstants;
import com.blankj.utilcode.util.EncodeUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.Utils;
import com.google.gson.Gson;
import com.ysalliance.getFan.organization.Bean.UserBean;

import org.litepal.LitePal;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

import static android.content.Context.INPUT_METHOD_SERVICE;
import static android.content.Context.MODE_PRIVATE;

/**
 *
 * @author lucas
 * created at 2019/2/20 11:52 AM
 */

public class LucasUtil {

    public static String get_kaoyan_daojishi(){
        Date kaoyan_date = TimeUtils.string2Date("2019-12-21 08:30:00");
        return String.valueOf(TimeUtils.getTimeSpanByNow(kaoyan_date, TimeConstants.DAY));
    }

    /**
     * 获取两个日期之间的日期，包括开始结束日期
     * @param start 开始日期
     * @param end 结束日期
     * @return 日期集合
     */
    public static List<Date> getBetweenDates(Date start, Date end) {
        List<Date> result = new ArrayList<Date>();
        Calendar tempStart = Calendar.getInstance();
        tempStart.setTime(start);
        tempStart.add(Calendar.DAY_OF_YEAR, 1);

        Calendar tempEnd = Calendar.getInstance();
        tempEnd.setTime(end);
        result.add(start);
        while (tempStart.before(tempEnd)) {
            result.add(tempStart.getTime());
            tempStart.add(Calendar.DAY_OF_YEAR, 1);
        }
        return result;
    }


    /**
     * 获取距离当前span_day天数的日期date
     * @author lucas
     * created at 2019/2/20 12:22 PM
     */
    public static Date get_between_date(int span_day){
        Calendar now = Calendar.getInstance();
        now.add(Calendar.DAY_OF_MONTH, span_day);
        return now.getTime();
    }

    /**
     * 获取首页日期的距离当前前后30天的日期
     * @author lucas
     * created at 2019/2/20 12:23 PM
     */
    public static List<Date> get_homepage_daylist(){
        List<Date> date_list = getBetweenDates(get_between_date(-30),get_between_date(30));
        return date_list;
    }



    /**
     * 时间戳转换成日期格式字符串
     * @param seconds 精确到秒的字符串
     * @param "formatStr"  "yyyy-MM-dd HH:mm"
     * @return
     */
    public static String timeStamp2Date(String seconds,String format) {
        if(seconds == null || seconds.isEmpty() || seconds.equals("null")){
            return "";
        }
        if(format == null || format.isEmpty()){
            format = "yyyy-MM-dd";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new Date(Long.valueOf(seconds+"000")));
    }



    /**
     * 存pref
     * @author lucas
     * created at 2018/12/5 12:45 PM
     */

    public static void pref_put(Context context, String name, String value){
        SharedPreferences.Editor editor = context.getSharedPreferences("faner_pref",MODE_PRIVATE).edit();
        editor.putString(name, value);
        editor.apply();
    }
       /**
     *
     * 获取pref
     * @author lucas
     * created at 2018/12/5 12:45 PM
     */
    public static String pref_get(Context context, String name){
        SharedPreferences pref = context.getSharedPreferences("faner_pref", MODE_PRIVATE);
        return pref.getString(name,"-1");
    }




    /**
     * 版本号比较
     *0代表相等，1代表version1大于version2，-1代表version1小于version2
     * @param version1
     * @param version2
     * @return
     */
    public static int compareVersion(String version1, String version2) {
        if (version1.equals(version2)) {
            return 0;
        }
        String[] version1Array = version1.split("\\.");
        String[] version2Array = version2.split("\\.");
        int index = 0;
        // 获取最小长度值
        int minLen = Math.min(version1Array.length, version2Array.length);
        int diff = 0;
        // 循环判断每位的大小
        while (index < minLen
                && (diff = Integer.parseInt(version1Array[index])
                - Integer.parseInt(version2Array[index])) == 0) {
            index++;
        }
        if (diff == 0) {
            // 如果位数不一致，比较多余位数
            for (int i = index; i < version1Array.length; i++) {
                if (Integer.parseInt(version1Array[i]) > 0) {
                    return 1;
                }
            }

            for (int i = index; i < version2Array.length; i++) {
                if (Integer.parseInt(version2Array[i]) > 0) {
                    return -1;
                }
            }
            return 0;
        } else {
            return diff > 0 ? 1 : -1;
        }
    }


    /**
     * 获取版本号
     *
     * @throws PackageManager.NameNotFoundException
     */
    public static String getVersionName(Context context) throws PackageManager.NameNotFoundException {
        // 获取packagemanager的实例
        PackageManager packageManager = context.getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
        String version = packInfo.versionName;
        return version;
    }



    /**
     * 获取七牛的外网连接的前缀
     *
     */
    public static String getQiniuWang(String content){
        return "http://xujinjn.cn/"+content;
    }


    /**
     * String转byte[]
     * @author lucas
     * created at 2019/4/23 2:47 PM
     */

    public static byte[] hexString2Bytes(String hexString) {
        if (isSpace(hexString)) return null;
        int len = hexString.length();
        if (len % 2 != 0) {
            hexString = "0" + hexString;
            len = len + 1;
        }
        char[] hexBytes = hexString.toUpperCase().toCharArray();
        byte[] ret = new byte[len >> 1];
        for (int i = 0; i < len; i += 2) {
            ret[i >> 1] = (byte) (hex2Int(hexBytes[i]) << 4 | hex2Int(hexBytes[i + 1]));
        }
        return ret;
    }
    private static boolean isSpace(final String s) {
        if (s == null) return true;
        for (int i = 0, len = s.length(); i < len; ++i) {
            if (!Character.isWhitespace(s.charAt(i))) {
                return false;
            }
        }
        return true;
    }
    private static int hex2Int(final char hexChar) {
        if (hexChar >= '0' && hexChar <= '9') {
            return hexChar - '0';
        } else if (hexChar >= 'A' && hexChar <= 'F') {
            return hexChar - 'A' + 10;
        } else {
            throw new IllegalArgumentException();
        }
    }


    /*
     * 中文转unicode编码
     */
    public static String gbEncoding(final String gbString) {
        char[] utfBytes = gbString.toCharArray();
        String unicodeBytes = "";
        for (int i = 0; i < utfBytes.length; i++) {
            String hexB = Integer.toHexString(utfBytes[i]);
            if (hexB.length() <= 2) {
                hexB = "00" + hexB;
            }
            unicodeBytes = unicodeBytes + "\\u" + hexB;
        }
        return unicodeBytes;
    }
    /*
     * unicode编码转中文
     */
    public static String decodeUnicode(final String dataStr) {
        int start = 0;
        int end = 0;
        final StringBuffer buffer = new StringBuffer();
        while (start > -1) {
            end = dataStr.indexOf("\\u", start + 2);
            String charStr = "";
            if (end == -1) {
                charStr = dataStr.substring(start + 2, dataStr.length());
            } else {
                charStr = dataStr.substring(start + 2, end);
            }
            char letter = (char) Integer.parseInt(charStr, 16); // 16进制parse整形字符串。
            buffer.append(new Character(letter).toString());
            start = end;
        }
        return buffer.toString();
    }

    /**
     * unicode转中文
     * @param str
     * @return
     * @author yutao
     * @date 2017年1月24日上午10:33:25
     */
    public static String unicodeToString(String str) {

        Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");

        Matcher matcher = pattern.matcher(str);

        char ch;

        while (matcher.find()) {

            ch = (char) Integer.parseInt(matcher.group(2), 16);

            str = str.replace(matcher.group(1), ch+"" );

        }

        return str;

    }


    /**
     * 获取随机颜色
     * @author lucas
     * created at 2019/5/4 10:41 AM
     */
    public static String getColor(){
        String[] colorarr = {
                "#b6c6d3",
                "#c2ecd8",
                "#67708d",
                "#bbdbda",
                "#20b1aa",

                "#bbdbda",
                "#8c9dc9",
                "#ef5555",
                "#bbdbda",
                "#696969",

                "#7ca9ac",
                "#708090",
                "#b6c6d3",
                "#ee7981",
                "#008b8a",

                "#67708d",
                "#b2a3e4",
                "#696969",
                "#283651",
                "#fcefe9",
        };
        return colorarr[new Random().nextInt(colorarr.length - 0)+ 0];
    }



    public  static int pixelToDp(Context context, int pixel) {
        DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
        return pixel < 0 ? pixel : Math.round(pixel / displayMetrics.density);
    }
    public  static int dpToPixel(Context context, int dp) {
        DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
        return dp < 0 ? dp : Math.round(dp * displayMetrics.density);
    }


    /**
     * 判断软键盘是否弹出
     * @author lucas
     * created at 2019/1/16 11:36 AM
     */
    public static boolean isSoftShowing(Activity activity) {
        //获取当屏幕内容的高度
        int screenHeight = activity.getWindow().getDecorView().getHeight();
        //获取View可见区域的bottom
        Rect rect = new Rect();
        //DecorView即为activity的顶级view
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
        //考虑到虚拟导航栏的情况（虚拟导航栏情况下：screenHeight = rect.bottom + 虚拟导航栏高度）
        //选取screenHeight*2/3进行判断
        return screenHeight*2/3 > rect.bottom;
    }

    /**
     * 隐藏软键盘
     * @author lucas
     * created at 2019/1/16 11:42 AM
     */
    public static void hide_softKeyboard(Activity activity){
        //如果键盘键存在，让它消失
        if(isSoftShowing(activity)){
            InputMethodManager imm = (InputMethodManager) activity.getSystemService(INPUT_METHOD_SERVICE);
            imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }


    /**
     * 检查是否安装qq
     * @author lucas
     * created at 2019/5/6 4:57 PM
     */
    public static boolean checkApkExist(Context context, String packageName) {
        if (packageName == null || "".equals(packageName))
            return false;
        try {
            ApplicationInfo info = context.getPackageManager().getApplicationInfo(packageName,
                    PackageManager.GET_UNINSTALLED_PACKAGES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }



    /**
     * 返回文字描述的日期
     *
     * @param
     * @return
     */
    //评论日期
    private final static long minute = 60 * 1000;// 1分钟
    private final static long hour = 60 * minute;// 1小时
    private final static long day = 24 * hour;// 1天
    private final static long month = 31 * day;// 月
    private final static long year = 12 * month;// 年
    public static String getTimeFormatText(String dateString) {

        Date date = null;
        try {
            date = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(dateString);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        if (date == null) {
            return null;
        }
        long diff = new Date().getTime() - date.getTime();
        long r = 0;
        if (diff > year) {
            r = (diff / year);
            return r + "年前";
        }
        if (diff > month) {
            r = (diff / month);
            return r + "个月前";
        }
        if (diff > day) {
            r = (diff / day);
            return r + "天前";
        }
        if (diff > hour) {
            r = (diff / hour);
            return r + "个小时前";
        }
        if (diff > minute) {
            r = (diff / minute);
            return r + "分钟前";
        }
        return "刚刚";
    }


    /**
     *
     * @author lucas
     * created at 2019/7/28 5:21 PM
     * 判断返回码状态
     */
    public static boolean isok(String resultCode){
        if(resultCode.equals("200"))
            return true;
        else
            return false;
    }


    //Util.java
    public static String getHour(String date) {
        //秒数
//		Integer dt = Integer.parseInt(date) ;
//		if (dt < 3600) return Math.round(dt / 60) + "分钟";
//		int hour = Math.round(dt / 3600);
//		int minute = Math.round((dt - (hour * 3600)) / 60);
//		return hour + "小时" + (minute == 0 ? "" : minute + "分钟");

        //分钟
        Integer dt = Integer.parseInt(date) ;
        if (dt < 60) return  "0'" + dt + "''";
        int hour = Math.round(dt / 60);
        int minute = Math.round(dt - (hour * 60));
        int seconds = Math.round(   dt -  (hour * 60)  - (minute * 60)    );
        return hour + "'" + (minute == 0 ? "" : minute + "''") ;
//        return hour + "'" + (minute == 0 ? "" : minute + "''")  + (seconds == 0 ? "" : seconds + "''");


    }


    public static boolean activityIsAlive(Context context) {
        if (context == null) {
            return false;
        }
        if (context instanceof Activity) {
            Activity activity = (Activity) context;
            return activityIsAlive(activity);
        } else {
            return true;
        }
    }

    public static boolean activityIsAlive(Activity activity) {
        if (activity == null) {
            return false;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            return !(activity.isDestroyed() || activity.isFinishing());
        } else {
            return !activity.isFinishing();
        }
    }


    /**
     *  EditText获取焦点并显示软键盘
     * @author lucas
     * created at 2019/1/16 11:41 AM
     * 如果弹不出来 在活动注册文件中添加
     *  android:windowSoftInputMode="stateAlwaysVisible"
     */
    public static void show_softKeyboard_focus_ed(Activity activity, EditText editText) {
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(editText, 0);
    }




    /**
     *
     * @author lucas
     * created at 2019/8/13 6:13 PM
     *
     *  计算time2减去time1的差值 差值只设置 几天 几个小时 或 几分钟
     *  根据差值返回多长之间前或多长时间后
     */
    public static String getDistanceTime(long time1, long time2) {
        long day = 0;
        long hour = 0;
        long min = 0;
        long sec = 0;
        long diff;

        if (time1 < time2) {
            diff = time2 - time1;
        } else {
            diff = time1 - time2;
        }
        day = diff / (24 * 60 * 60 * 1000);
        hour = (diff / (60 * 60 * 1000) - day * 24);
        min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
        sec = (diff / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
        if (day != 0) return day + "天"+hour + "小时"+min + "分钟" + sec + "秒";
        if (hour != 0) return hour + "小时"+ min + "分钟" + sec + "秒";
        if (min != 0) return min + "分钟" + sec + "秒";
        if (sec != 0) return sec + "秒" ;
        return "0秒";
    }

    public static String[] getDistanceTime2(long time1, long time2) {
        long day = 0;
        long hour = 0;
        long min = 0;
        long sec = 0;

        long diff;

        if (time1 < time2) {
            diff = time2 - time1;
        } else {
            diff = time1 - time2;
        }

        day = diff / (24 * 60 * 60 );
        hour = (diff / (60 * 60 ) - day * 24);
        min = ((diff / (60 )) - day * 24 * 60 - hour * 60);
        sec = (diff  - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);


        String[] jj = new String[4];
        jj[0] = day+"";
        jj[1] = hour + "";
        jj[2] = min + "";
        jj[3] = sec + "";

        return jj;

    }


    public static String getDistanceTime3(long time1, long time2) {
        long day = 0;
        long hour = 0;
        long min = 0;
        long sec = 0;
        long diff;

        if (time1 < time2) {
            diff = time2 - time1;
        } else {
            diff = time1 - time2;
        }
        min = (     (diff / (60 * 1000))     );
        return min+"分";
    }


    /**
     *
     * @author lucas
     * created at 2019/8/20 5:40 PM
     *
     * 把数字时长转化为时间字符串
     */
    public static String getTimeFromInt(int time) {

        if (time <= 0) {
            return "0:00";
        }
        int secondnd = (time / 1000) / 60;
        int million = (time / 1000) % 60;
        String f = String.valueOf(secondnd);
        String m = million >= 10 ? String.valueOf(million) : "0"
                + String.valueOf(million);
        return f + ":" + m;
    }


    /**
     * 判断给定字符串是否空白串 空白串是指由空格、制表符、回车符、换行符组成的字符串 若输入字符串为null或空字符串，返回true
     */
    public static boolean isEmpty(CharSequence input) {
        if (input == null || "".equals(input) || "null".equals(input))
            return true;

        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            if (c != ' ' && c != '\t' && c != '\r' && c != '\n') {
                return false;
            }
        }
        return true;
    }



    /**
     * 根据手机分辨率从 dp 单位 转成 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }








    /**
     *
     * @author lucas
     * created at 2019/8/23 2:41 PM
     *
     * 根据id获取网络连接
     *
     */
    public static String getMusicUrl(String string){
        return "https://oss.getfan.cn/app/"+string;
    }





    /**
     * faner下载的本地路径
     * @author lucas
     * created at  6:08 PM
     */
    public static String getFanerDir(){
        return Environment.getExternalStorageDirectory().getPath() + "/faner/music/";
    }

    /**
     * 返回mp3的歌曲名字
     * @author lucas
     * created at 2019/9/16 6:10 PM
     */
    public static String getMp3NameFromHttp(String httpName){
        if(httpName!=null){
            String[] temp_mp3 = httpName.split("/");
            return temp_mp3[temp_mp3.length-1];
        }else {
            return "";
        }

    }







    /**
     * 首页10分钟内刷新
     * @author lucas
     * created at 2019/11/13 12:09 PM
     */
    public static Boolean getIfFresh(Context mContext){
        if( LucasUtil.pref_get(mContext,"首页时间").equals("-1")){
            setIfFreshTime(mContext);
            return true;
        }else if( TimeUtils.getNowMills() - (Long.parseLong(LucasUtil.pref_get(mContext,"首页时间"))) > (60*1000)){
            setIfFreshTime(mContext);
            return true;
        }else {
            return false;
        }
    }
    /**
     * 首页10分钟内刷新  写入首页时间
     * @author lucas
     * created at 2019/11/13 12:09 PM
     */
    public static void setIfFreshTime(Context mContext){
        LucasUtil.pref_put(mContext,"首页时间", TimeUtils.getNowMills()+"");
    }


    public static String  getBase64Refer(String baseString){
        String prim = EncodeUtils.base64Encode2String(baseString.getBytes());
        String first8 = prim.substring(0,8);
        String sec4 = prim.substring(8,12);
        String lastall = prim.substring(12,prim.length()-1);
        return first8+lastall+sec4;
    }


    public static  boolean  is_allow(Context context){
       if(LucasUtil.pref_get(context,"is_allow").equals("-1")){
           return true;
       }else {
           return false;
       }
    }


    /**
     * dip转为PX
     */
    public static int musicDip2px(Context context, float dipValue) {
        float fontScale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * fontScale + 0.5f);
    }






    /**
     * sina
     * 判断是否安装新浪微博
     */
    public static boolean isSinaInstalled(Context context){
        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.sina.weibo")) {
                    return true;
                }
            }
        }

        return false;
    }



    /**
     * 登陆的同一方法
     */
    public static boolean login_related(Context context, String user_info){
        LitePal.deleteAll(UserBean.class);
        UserBean userBean = new Gson().fromJson(user_info, UserBean.class);
        boolean issave = userBean.save();
        return issave;
    }


    /**
     * 登陆的同一方法
     */
    public static boolean isLogin(){
        if(LitePal.findFirst(UserBean.class)!=null){
           return true;
        }else {
            return false;
        }
    }





}
